package com.example.mediamoudle.crop;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.util.Size;
import android.view.*;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.baselibrary.utils.ScreenUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.example.mediamoudle.R;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import static androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_IDLE;

/**
 * @author: Mr.You
 * @create: 2022-11-22 10:08
 * @description:
 **/
public class VideoFrameView extends FrameLayout implements ThumbnailProgressView.OnScrollBorderListener {
    private RecyclerView mThumbPreview;//缩略图预览
    private ImageView mSplitView;
    private  int mThumbHeight = 50;
    private ThumbAdapter thumbAdapter;
    private  Size mLayoutSize = new Size(0, 0);
    private int mCacheScrollX = 0;
    private List<VideoInfo> mInfoList;
    /**
     * 编辑页 裁剪设置最大值
     */
    private  int EDITE_CROP_MAX_TIME = 60;

    /**
     * 编辑页 裁剪设置最小值
     */
    private  int EDITE_CROP_MIN_TIME = 3;
    /** 裁剪轨道时间轴*/
    private ThumbnailProgressView mThumbProgressView;
    RecycleViewScrollListener mListener;
    public VideoFrameView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
        bindViewTreeCallback();

    }


    private void initView() {
        mThumbHeight = dp2px(mThumbHeight);
        LayoutInflater.from(getContext()).inflate(R.layout.layout_video_frame, this);
        mThumbPreview = findViewById(R.id.mRecyclerView);

        mThumbPreview.addItemDecoration(new RecyclerDivider(getContext().getResources().getColor(com.android.baselibrary.R.color.color_808080)));
        thumbAdapter = new ThumbAdapter();
        mThumbPreview.setAdapter(thumbAdapter);

        mThumbProgressView = findViewById(R.id.thumbProgressView);
        mThumbProgressView.setMinInterval(mThumbHeight*EDITE_CROP_MIN_TIME);

    }
    boolean isScroll = false;

    @SuppressLint("ClickableViewAccessibility")
    private void bindViewTreeCallback() {
        mThumbProgressView.setOnScrollBorderListener(this);
        getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    mLayoutSize = new Size(ScreenUtils.getScreenWidth(getContext(), false) ,getMeasuredHeight());
                }
                getViewTreeObserver().removeOnGlobalLayoutListener(this);
               // updateData(mVideoState);
            }
        });
        mThumbPreview.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull @NotNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                Log.i("TAGnewState", "onScrollStateChanged: "+newState);
                if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                    mListener.pause();
                } else if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    mListener.start();
                }
               // updateCorrectScrollX();
            }

            @Override
            public void onScrolled(@NonNull @NotNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Log.i("TAGnewState", "onScrolled: "+dx);
                updateCorrectScrollX();
                mThumbProgressView.setBitmapScroll(dx);
                if (recyclerView.getScrollState() != SCROLL_STATE_IDLE&& !mListener.getPlayerState()) {
                    mListener.seekToPosition((long) (1000.f / mThumbHeight * mCacheScrollX));
                }
                // 屏幕可见的数量
                int childSize = recyclerView.getChildCount();
                int left = 0;
                int right = 0;
                int mLeftRight =0;
                int mLeft0 =0;
                for (int i=0;i<childSize - 1;i++){
                    View child = recyclerView.getChildAt(i);
                    left = child.getLeft();
                    right = child.getRight();
                    mLeftRight = right - left;
                    if (i == 1) {
                        mLeft0 = left;
                        mThumbProgressView.setMaxLeft(left);
                    } else if (i == childSize - 2) {
                        mThumbProgressView.setMaxRight(right);
                    }
                }

            }


        });
        mThumbPreview.setOnTouchListener((v, event) -> {
            switch (event.getAction()){
                case MotionEvent.ACTION_DOWN :
                    isScroll = true;
                    break;
                case MotionEvent.ACTION_MOVE:
                        break;
                case MotionEvent.ACTION_UP:
                    isScroll = false;
                    break;

            }
            return false;
        });
    }
    private void updateCorrectScrollX() {
        LinearLayoutManager layoutManager = (LinearLayoutManager) mThumbPreview.getLayoutManager();
        int firstPos = layoutManager.findFirstVisibleItemPosition();
        if (firstPos == 0) {
            mCacheScrollX = -layoutManager.findViewByPosition(0).getLeft();
        } else {
            int totalScroll = 0;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                totalScroll = mLayoutSize.getWidth() / 2;
            }
            for (int i = 1; i < firstPos; i++) {

                totalScroll += 1000000 / 1000000.f * mThumbHeight;
                Log.i("TAG", "updateCorrectScrollX: "+totalScroll);
            }
            totalScroll += -layoutManager.findViewByPosition(firstPos).getLeft();
            mCacheScrollX = totalScroll;
            Log.i("TAG", "1updateCorrectScrollX22: "+mCacheScrollX);
        }
    }
    public void updateScroll(boolean isSmooth, long time) {
        int correctScrollX = (int) (mThumbHeight / 1000000.f * time);
        mThumbPreview.smoothScrollBy(correctScrollX - mCacheScrollX, 0);


    }
    public void setRecycleViewScrollListener(RecycleViewScrollListener listener){
        this.mListener = listener;
    }

    public void setThumbList(List<VideoInfo> list){
        this.mInfoList = list;
        thumbAdapter.updateList(list);
        if (list.size()-2 < EDITE_CROP_MAX_TIME) {
            int thumbProgressWidth = mThumbHeight*(list.size()-2);
            mThumbProgressView.setWidth(thumbProgressWidth);
            mThumbProgressView.setTextShow("%.1f".format((list.size()-2)+"") + "s");

        } else {
            int thumbProgressWidth = mThumbHeight*EDITE_CROP_MAX_TIME;
            mThumbProgressView.setWidth(thumbProgressWidth);
            mThumbProgressView.setTextShow(String.format("%.1f",Double.valueOf(EDITE_CROP_MAX_TIME)) + "s");
        }
    }
    private int dp2px(int dp) {
        return (int) (dp * getContext().getResources().getDisplayMetrics().density);
    }

    @Override
    public void OnScrollBorder(float start, float end) {

    }

    @Override
    public void onScrollStateChange() {

    }

    interface RecycleViewScrollListener{
        void start();
        void pause();
        void seekToPosition(long position);
        boolean getPlayerState();
    }
}
